//
//  HXDLocationManager.m
//  qingDaoCircleOfLife
//
//  Created by huxuedong on 15/11/22.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

#import "HXDLocationManager.h"

@interface HXDLocationManager () <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *manager;
@property (copy, nonatomic) successLocal success;
@property (copy, nonatomic) errorLocal error;
//本地是否需要更新位置的标识
@property (assign, nonatomic) BOOL local;

@end

@implementation HXDLocationManager

- (instancetype)init {
    if (self = [super init]) {
        self.manager = [[CLLocationManager alloc] init];
        //判断请求是否总是被授权
        if ([self.manager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.manager requestAlwaysAuthorization];
        }
        self.manager.delegate = self;
    }
    return self;
}

+ (instancetype)shareInstance {
    static id manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[HXDLocationManager alloc] init];
    });
    return manager;
}

- (void)localWithSuccess:(successLocal)success orError:(errorLocal)error {
    //开始更新位置数据
    [self.manager startUpdatingLocation];
    self.local = NO;
    self.success = success;
}

+ (void)localWithSuccess:(successLocal)success orError:(errorLocal)error {
    [[self shareInstance] localWithSuccess:success orError:error];
}

#pragma mark --- CLLocationManagerDelegate的代理方法

//授权状态改变时调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    //如果取消授权，则停止更新位置数据
    if (status == kCLAuthorizationStatusDenied) {
        [self.manager stopUpdatingLocation];
    }
}

//更新位置完成之后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [self.manager stopUpdatingLocation];
    if (locations.count > 0) {
        CLLocation *location = locations.lastObject;
        if (!self.local) {
            //将位置坐标回调
            self.success(location.coordinate);
            self.local = YES;
        }
    }
}

//定位失败调用
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self.manager stopUpdatingLocation];
//    self.error(error);
}

@end
